package com.wzy.scns.controller;

import com.wzy.scns.entity.Course;
import com.wzy.scns.entity.SelectCourse;
import com.wzy.scns.entity.Teacher;
import com.wzy.scns.repositery.StudentRepository;
import com.wzy.scns.repositery.CourseRepository;
import com.wzy.scns.repositery.SelectCourseRepository;
import com.wzy.scns.repositery.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.*;

@Validated
@RestController
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    TeacherRepository teacherRepository;
    @Autowired
    SelectCourseRepository selectCourseRepository;
    @Autowired
    CourseRepository courseRepository;
    @Autowired
    StudentRepository studentRepository;

    @Validated
    @PostMapping("/add")
    public Map add(@NotNull(message = "姓名不能为空") String name,
                   @NotNull(message = "工号不能为空") String code,
                   @RequestParam(defaultValue = "") String phone,
                   @NotNull(message = "密码不能为空") String password,
                   @NotNull(message = "系部不能为空") String department,
                   @RequestParam(defaultValue = "") String sex) {
        List<String> msgs = new ArrayList<>();
        if (teacherRepository.findByCode(code) != null)
            msgs.add("工号已存在");
        if (teacherRepository.findByName(name) != null)
            msgs.add("姓名已存在");
        if (msgs.size() > 0)
            return makeErrorMap(msgs);
        Teacher teacher = new Teacher();
        teacher.setCode(code);
        teacher.setName(name);
        teacher.setPhone(phone);
        teacher.setPassword(password);
        teacher.setDepartment(department);
        if (sex.length() == 0)
            teacher.setSex(sex);
        if (teacherRepository.save(teacher) != null)
            return postMap("注册成功", 1);
        return errorMap("注册失败");
    }

    @PostMapping("/updataById")
    public Map updataById(
            @NotNull(message = "Id不能为空") Integer id,
            @NotNull(message = "姓名不能为空") String name,
            @NotNull(message = "工号不能为空") String code,
            String phone,
            @NotNull(message = "密码不能为空") String password,
            @NotNull(message = "系部不能为空") String department,
            String sex) {
        Teacher teacherById = teacherRepository.findById(id).get();
        List<String> msgs = new ArrayList<>();
        if (teacherById == null)
            return errorMap("未找到该工号所匹配的教师");
        if (teacherRepository.findByCodeAndIdIsNot(code, teacherById.getId()) != null)
            msgs.add("工号已存在");
        if (teacherRepository.findByNameAndIdIsNot(name, teacherById.getId()) != null)
            msgs.add("姓名已存在");
        if (msgs.size() > 0)
            return makeErrorMap(msgs);
        teacherById.setSex(sex);
        teacherById.setName(name);
        teacherById.setCode(code);
        teacherById.setPhone(phone);
        teacherById.setPassword(password);
        teacherById.setDepartment(department);
        teacherRepository.save(teacherById);
        return postMap("修改成功", 1);
    }

    //查询
    //姓名密码登录
//    @GetMapping("/login")
//    public Map login(@NotNull String name, @NotNull String password) {
//        Map map = new HashMap();
//        Teacher teacher = teacherRepository.findByNameAndPassword(name, password);
//        if (teacher != null)
//            return getMap("登录成功",teacher);
//        teacher = teacherRepository.findByName(name);
//        if(teacher==null)
//            return errorMap("工号不存在");
//        return errorMap("密码错误");
//    }
    //查询
    //工号密码登录
    @GetMapping("/login")
    public Map login(@NotNull String code, @NotNull String password) {
        Teacher teacher = teacherRepository.findByCodeAndPassword(code, password);
        if (teacher != null)
            return getMap("登录成功", teacher);
        teacher = teacherRepository.findByName(code);
        if (teacher == null)
            return errorMap("工号不存在");
        return errorMap("密码错误");
    }


    //    教师管理功能需求：教师注册，教师修改自己的信息，
//    教师删除，教师能查询自己单门课程的选课信息，
//    教师能分析自己的所有课程成绩统计信息（每门课的平均分，最高分，最低分等）。
    @PostMapping("/delete")
    public Map deleteTeacher(@NotNull Integer id) {
        if (courseRepository.findAllByTeacherId(id).size() > 0)
            return errorMap("该教师目前还有课程未关闭");
        teacherRepository.deleteById(id);
        return postMap("删除成功", 1);
    }

    @GetMapping("/getAllCourseByCode")
    public Page<Course> getAllCourseByCode(@NotNull String teacherCode, @RequestParam(defaultValue = "0") Integer currentPage, @RequestParam(defaultValue = "5") Integer pageSize) {
        Teacher teacher = teacherRepository.findByCode(teacherCode);
        Pageable pageable = PageRequest.of(currentPage, pageSize, Sort.Direction.ASC, "code");
        return courseRepository.findByTeacherId(teacher.getId(), pageable);
    }

    //根据课程名、教师id模糊匹配
    @GetMapping("/getCourseByCourseNameAndTeacherCode")
    public Page<Course> getCourseByCourseNameAndTeacherCode(@NotNull String teacherCode, @NotNull String courseName, @RequestParam(defaultValue = "0") Integer currentPage, @RequestParam(defaultValue = "5") Integer pageSize) {
        Teacher teacher = teacherRepository.findByCode(teacherCode);
        Pageable pageable = PageRequest.of(currentPage, pageSize, Sort.Direction.ASC, "code");
        return courseRepository.findByNameIsContainingAndTeacherId(courseName, teacher.getId(), pageable);
    }

    @GetMapping("/getCourseByCode")
    public Map getCourseByCode(@NotNull String teacherCode, @NotNull String courseCode) {
        Teacher teacher = teacherRepository.findByCode(teacherCode);
        Map mapResp = new HashMap();
        Map student = new HashMap();
        //该课程选课记录，取学号
        mapResp.put("courseDetail", courseRepository.findByCodeAndTeacherId(courseCode, teacher.getId()));
        List<SelectCourse> sc = selectCourseRepository.findByCourseCode(courseCode);
        if (sc.size()==0)
            return getMap("暂无学生选修该课程",null);
        for (int i = 0; i < sc.size(); i++) {
            Map map = new HashMap();
            map.put("StudentCode", sc.get(i).getStudentCode());
            map.put("Achievement", sc.get(i).getAchievement());
            map.put("StudentName", studentRepository.findByCode(sc.get(i).getStudentCode()).getName());
            student.put(i + 1, map);
        }
        mapResp.put("student", student);
        mapResp.put("total", student.size());
        return getMap("查询成功", mapResp);
        //返回学号、姓名、成绩
    }

    //实现根据课程名称，统计查询课程的最高分、最低分、平均分的接口
    @GetMapping("/getAllAnalysisMsg")
    public Map getAllAnalysisMsg(@NotNull String teacherCode,@RequestParam(defaultValue = "0") Integer currtPage,@RequestParam(defaultValue = "5") Integer pageSize) {
        //获取教师id
        Teacher teacher = teacherRepository.findByCode(teacherCode);
        List list = new ArrayList();
        //获取教师所有课程
        List<Course> courses = courseRepository.findAllByTeacherId(teacher.getId());
        //该课程选课记录，取学号
        int maxIndex = currtPage*pageSize+pageSize;
        if (maxIndex>courses.size())
            maxIndex = courses.size();
        for (int i = currtPage*pageSize; i < maxIndex; i++) {
            Float[] arr = selectCourseRepository.getMaxMinAvgByCCode(courses.get(i).getCode());
            Map map2 = new HashMap();
            map2.put("courseName", courses.get(i).getName());
            map2.put("courseCode", courses.get(i).getCode());
            map2.put("totalStudent", arr.length);
            if (arr.length <= 0) {
                map2.put("average", "暂无数据");
                map2.put("max", "暂无数据");
                map2.put("min", "暂无数据");
                list.add(map2);
                continue;
            }
            Arrays.sort(arr);
            map2.put("average", Avg(arr));
            map2.put("max", arr[arr.length - 1]);
            map2.put("min", arr[0]);
            list.add(map2);
        }
        Map map = new HashMap();
        map.put("code",1);
        map.put("data",list);
        map.put("total",courses.size());
        return map;
    }

    public Float Avg(Float[] arr) {
        float sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        return sum / arr.length;
    }

    public Map makeErrorMap(List<String> msg) {
        Map map = new HashMap();
        map.put("msg", msg);
        map.put("code", 201);
        return map;
    }


    public Map getMap(String msg, Object data) {
        Map map = new HashMap();
        map.put("data", data);
        map.put("msg", msg);
        map.put("code", 1);
        return map;
    }

    public Map postMap(String msg, Integer totalSelf) {
        Map map = new HashMap();
        map.put("code", 1);
        map.put("msg", msg);
        map.put("total", totalSelf);
        return map;
    }

    public Map errorMap(String msg) {
        Map map = new HashMap();
        map.put("code", 0);
        map.put("msg", msg);
        return map;
    }
}
